package com.seo.controller.keyWord;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.seo.function.PageTool;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.KeywordGService;
import com.seo.service.keyword.sdk.KeywordService;
import com.seo.service.keyword.sdk.NewStationService;
import com.seo.utils.ClientConst;
import com.seo.utils.DateUtil;
import com.seo.utils.Jurisdiction;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: 关键词新站Controller
 * @author rtc
 * @version 2019.10.18 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "newStation/")
public class NewStationController {

	@Resource(name = "newStationService")
	private NewStationService newStationService;
	
	@Autowired
	private KeywordGService keywordGService;
	
	@Autowired
	private PageTool pageTool;
	
	@Resource(name = "keywordService")
	private KeywordService keywordService;

	/**
	 * 新站网站列表
	 * @param param param
	 * @param request request
	 * @return String
	 */
	@RequestMapping(value = "/list")
	public String list(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		log.info("进入新站网站列表...");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		param.put("userType", "customer");
		param.put("userId", user.get("id"));
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getNewDomainList, param);
		request.setAttribute("page", page);
		request.setAttribute("param", param);
		request.setAttribute("venderList", venderList);
		return "newStation/new_station_list";
	}
	
	/**
	 * 新站网站下级列表
	 * @param param param
	 * @param request request
	 * @return String
	 */
	@RequestMapping(value = "/lowerList")
	public String lowerList(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		log.info("进入新站网站下级列表...");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		param.put("userType", "lower");
		param.put("userId", user.get("id"));
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getNewDomainList, param);
		request.setAttribute("page", page);
		request.setAttribute("param", param);
		request.setAttribute("venderList", venderList);
		return "newStation/new_station_lower_list";
	}
	
	/**
	 * 跳转网站新增
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toAdd")
	public String toKeyWordAdd(HttpServletRequest request) throws Exception {
		log.info("【跳转网站新增】---【开始】---");
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		request.setAttribute("venderList", venderList);
		request.setAttribute("msg", "saveNewKeywordsDomainCustomer");
		log.info("【跳转网站新增】---【结束】---");
		return "newStation/new_station_add";
	}
	
	/**
	 * 新增新站网站
	 * @param params params
	 * @return ReturnBody
	 */
	@RequestMapping("/saveNewKeywordsDomainCustomer")
	public String saveNewKeywordsDomain(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("【新增新站网站】---【开始】---");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		if(user == null || user.isEmpty() || params == null || params.isEmpty()) {
			rb.error("参数有误");
			request.setAttribute("result", rb.getResult());
			return "save_result";
		}
		params.put("user", user);
		params.put("create_id", user.get("id"));
		try {
			rb = newStationService.saveNewKeywordsDomainCustomer(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("【新增新站网站】---【结束】---");
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 跳转网站编辑
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toEdit")
	public String toEdit(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		log.info("【跳转网站编辑】---【开始】---");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		params.put("userType", "customer");
		params.put("userId", user.get("id"));
		List<Map<String, Object>> newDomainList = newStationService.getNewDomainList(params);
		if(newDomainList != null && newDomainList.size()>0) {
			request.setAttribute("info", newDomainList.get(0));
		}
		request.setAttribute("venderList", venderList);
		request.setAttribute("msg", "updateNewKeywordsDomain");
		log.info("【跳转网站编辑】---【结束】---");
		return "newStation/new_station_add";
	}
	
	/**
	 * 编辑新站网站
	 * @param params params
	 * @return ReturnBody
	 */
	@RequestMapping("/updateNewKeywordsDomain")
	public String updateNewKeywordsDomain(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("【编辑新站网站】---【开始】---");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		params.put("update_id", user.get("id"));
		ReturnBody rb = ReturnBody.init();
		try {
			rb =  newStationService.updateNewKeywordsDomain(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("【编辑新站网站】---【结束】---");
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 修改网站状态
	 * @param param param
	 * @param request request
	 * @return ReturnBody
	 */
	@RequestMapping(value = "/updateDomainState")
	@ResponseBody
	public ReturnBody updateDomainState(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		log.info("修改网站状态开始...");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		if(param == null || param.size() == 0) {
			rb.error("缺少参数");
		}
		param.put("update_id", user.get("id"));
		rb = newStationService.updateDomainState(param);
		log.info("修改网站状态结束...");
		return rb;
	}
	
	/**
	 * 跳转新增网站关键词页面
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toKeywordsAdd")
	public String toKeywordsAdd(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		log.info("【跳转新增网站关键词页面】---【开始】---");
		List<Map<String, Object>> engine = keywordService.getEngineList();
		request.setAttribute("engine", engine);
		request.setAttribute("params", params);
		log.info("【跳转新增网站关键词页面】---【结束】---");
		return "newStation/domain_keyWord_add";
	}
	
	/**
	 * 网站关键词新增
	 * @param param  param
	 * @return ReturnBody
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/add")
	@ResponseBody
	public ReturnBody add(@RequestParam Map<String, Object> param) throws Exception {
		log.info("【客户网站关键词新增】---【开始】---");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		try {
			if (param == null || param.isEmpty() || user == null || user.isEmpty()) {
				return rb.error("参数不能为空");
			}
			if (!param.containsKey("userName")) {
				return rb.error("请输入用户名");
			}
			if (!param.containsKey("engineCode")) {
				return rb.error("请选择搜索引擎");
			}
			param.put("createId", 0);
			param.put("user", user);
			rb.run(newStationService.saveDomainKeyWordToCustomer(param));
			log.info("【客户关键词新增】---【结束】---");
		} catch (Exception e) {
			log.error("网站关键词新增异常[{}]", e);
			return rb.error();
		}
		return rb;
	}
	/*
	 * 代理关键字列表
	 */
	@RequestMapping("/proxyList")
	public String proxyList(@RequestParam Map<String, Object> pam,HttpServletRequest request, HttpSession session) {
		log.info("进入代理关键字列表...");
		List<Map<String, Object>> venderList = newStationService.getVenderList(); //厂商列表
		List<Map<String, Object>> engineList = newStationService.getEngineList(); //搜索引擎列表
		Integer userId = 0;
		if(pam.containsKey("userId") ) {
			String userIdStr = (String) pam.get("userId");
			if(StringUtils.isNotBlank(userIdStr)) {
				userId = Integer.valueOf(userIdStr);
			}else {
				userId = Jurisdiction.getT("id", Integer.class);
			}
		}else {
			userId = Jurisdiction.getT("id", Integer.class);
		}
		List<Map<String, Object>> groupList =  newStationService.getGroupByUserId(userId); //所在分组
		pam.put("userId", userId);
		//排名区间 1：1-10 2：11-50 3： 51-100 4: 100+
		String rankingInterval = (String) pam.get("rankingInterval");
		if(StringUtils.isNotBlank(rankingInterval)) {
			String startRanking = null;
			String endRanking = null;
			if("1".equals(rankingInterval)) {
				startRanking = "1";
				endRanking = "10";
			}else if("2".equals(rankingInterval)) {
				startRanking = "11";
				endRanking = "50";
			}else if("3".equals(rankingInterval)) {
				startRanking = "51";
				endRanking = "100";
			}else {
				startRanking = "100";
			}
			pam.put("startRanking", startRanking);
			pam.put("endRanking", endRanking);
		}		
		
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getKeyWordsEList,pam);
		request.setAttribute("page", page);
		request.setAttribute("venderList", venderList);
		request.setAttribute("groupList", groupList);
		request.setAttribute("engineList", engineList);
		request.setAttribute("pam", pam);
		return "newStation/keyWord_list";

	}

	/**
	 * 进入分组页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editGroupPage")
	public String editGroupPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入分组页面");
		Integer userId = Jurisdiction.getT("id", Integer.class);
		List<Map<String, Object>> groupList =  newStationService.getGroupByUserId(userId);
		request.setAttribute("groupList", groupList);
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editGroup");
		return "newStation/group_edit";
	}
	
	/**
	 * 进行分组
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editGroup")
	public String editGroup(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改厂商");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updateGroupById(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 进入价格修改页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editPricePage")
	public String editPricePage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入价格页面");
		request.setAttribute("targetRanking", pam.get("targetRanking"));
		request.setAttribute("price", pam.get("price"));
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editPrice");
		return "newStation/price_edit";
	}
	
	@RequestMapping("/editPrice")
	public String editPrice(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改价格");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updateChaildPrice(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/*
	 * 代理下级关键字列表
	 */
	@RequestMapping("/proxyLowerList")
	public String proxyLowerList(@RequestParam Map<String, Object> pam,HttpServletRequest request, HttpSession session) {
		log.info("进入代理下级关键字列表...");
		List<Map<String, Object>> venderList = newStationService.getVenderList(); //厂商列表
		List<Map<String, Object>> engineList = newStationService.getEngineList(); //搜索引擎列表
		Integer userId = Jurisdiction.getT("id", Integer.class);
		List<Map<String, Object>> groupList =  newStationService.getGroupByUserId(userId); //所在分组
		pam.put("parentId", userId);
		//排名区间 1：1-10 2：11-50 3： 51-100 4: 100+
		String rankingInterval = (String) pam.get("rankingInterval");
		if(StringUtils.isNotBlank(rankingInterval)) {
			String startRanking = null;
			String endRanking = null;
			if("1".equals(rankingInterval)) {
				startRanking = "1";
				endRanking = "10";
			}else if("2".equals(rankingInterval)) {
				startRanking = "11";
				endRanking = "50";
			}else if("3".equals(rankingInterval)) {
				startRanking = "51";
				endRanking = "100";
			}else {
				startRanking = "100";
			}
			pam.put("startRanking", startRanking);
			pam.put("endRanking", endRanking);
		}		
		
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getKeyWordsEList,pam);
		request.setAttribute("page", page);
		request.setAttribute("venderList", venderList);
		request.setAttribute("groupList", groupList);
		request.setAttribute("engineList", engineList);
		request.setAttribute("pam", pam);
		return "newStation/keylowerWord_list";

	}

	/**
	 * 启用停用
	 * @param pam
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/keyWordEnable")
	@ResponseBody
	public String keyWordEnable(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词启用停用方法...");
		String msg = "";// 01 成功    02 失败   03 您的关键词最少要使用15天    04 您的关键词最少要达标30天
		String oldState = (String) pam.get("oldState"); // 原来的状态
		String newState = (String) pam.get("newState"); // 现有的状态 也就是所要修改的状态
		String id = (String) pam.get("ids");//关键词主键
		Map<String, Object> p = new HashMap<>();
		p.put("id", id);
		Map<String, Object> keyword = newStationService.getInfoBykeywordId(p);
		int reachDays = (int) keyword.get("reach_days");//达标天数
		String createTime = (String) keyword.get("create_time");//时间
		if(reachDays == 0) {
			Long dayNum = DateUtil.getDaySub(createTime, DateUtil.getTime());
			if(dayNum>15) {
				if("01".equals(newState)){ // 如果现有状态 为01 使用中  那么原来的状态 必须为02 已停用
					if("02".equals(oldState)){
						pam.put("state", newState);
						try {
							newStationService.updatekeyWordReviewDisabled(pam);
							msg = "01";
						} catch (Exception e) {
							msg = "02";
						}
					}
				}else if("02".equals(newState)){ // 如果现有状态 为02 已停用  那么原来的状态 必须为01  使用中
					if("01".equals(oldState)){
						pam.put("state", newState);
						try {
							newStationService.updatekeyWordReviewDisabled(pam);
							msg = "01";
						} catch (Exception e) {
							msg = "01";
						}
					}
				}
			}else {
				msg = "03";
			}
		}else {
				if(reachDays>30) {
					if("01".equals(newState)){ // 如果现有状态 为01 使用中  那么原来的状态 必须为02 已停用
						if("02".equals(oldState)){
							pam.put("state", newState);
							try {
								newStationService.updatekeyWordReviewDisabled(pam);
								msg = "01";
							} catch (Exception e) {
								msg = "02";
							}
						}
					}else if("02".equals(newState)){ // 如果现有状态 为02 已停用  那么原来的状态 必须为01  使用中
						if("01".equals(oldState)){
							pam.put("state", newState);
							try {
								newStationService.updatekeyWordReviewDisabled(pam);
								msg = "01";
							} catch (Exception e) {
								msg = "02";
							}
						}
					}
				}else {
					msg = "04";
				}
		}
		return msg;
	}
}
